package com.luck.easyfoodbatch.ui;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.mine.MemberInfoModel;
import com.luck.easyfoodbatch.mvp.mine.MemberInfoPresenter;
import com.luck.easyfoodbatch.mvp.mine.MemberInfoView;
import com.luck.easyfoodbatch.mvp.mine.PreviewPromotionModel;
import com.luck.easyfoodbatch.mvp.mine.PreviewPromotionPresenter;
import com.luck.easyfoodbatch.mvp.mine.PreviewPromotionView;
import com.luck.easyfoodbatch.mvp.mine.PromotionGoodsModel;
import com.luck.easyfoodbatch.mvp.mine.PromotionGoodsPresenter;
import com.luck.easyfoodbatch.mvp.mine.PromotionGoodsView;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.MyGoods;
import com.luck.easyfoodbatch.mvp.model.PreviewM;
import com.luck.easyfoodbatch.mvp.model.UserModel;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ExtensionActivity extends BaseActivity implements PromotionGoodsView, MemberInfoView, PreviewPromotionView {
    @BindView(R.id.rl_extension)
    RelativeLayout rlExtension;
    @BindView(R.id.rl_apply)
    RelativeLayout rlApply;
    private MyGoods.DataBean.ModelsBean bean;
    @BindView(R.id.iv_banner)
    ImageView iv_banner;
    @BindView(R.id.tv_goods_name)
    TextView tv_goods_name;
    @BindView(R.id.tv_spec)
    TextView tv_spec;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_place)
    TextView tv_place;
    @BindView(R.id.tv_stock)
    TextView tv_stock;
    @BindView(R.id.iv_expiring)
    ImageView iv_expiring;
    @BindView(R.id.tv_city)
    TextView tv_city;
    @BindView(R.id.input_search_query)
    EditText input_search_query;
    @BindView(R.id.tv_my_point)
    TextView tv_my_point;
    @BindView(R.id.tv_to_point)
    TextView tv_to_point;
    @BindView(R.id.ll_root)
    LinearLayout ll_root;
    private String gid = "";
    private PromotionGoodsModel goodsModel;
    private String areas = "";
    private PreviewPromotionModel promotionModel;
    private User user;
    private int point = 0;
    private List<String> values = new ArrayList<>();
    private LayoutInflater inflater;
    private int to_point = 0;
    private MemberInfoModel memberInfoModel;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("action.app.integral")) {
                if (!Tools.isNull(user.getPoint())) {
                    user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                    point = user.getPoint();
                    tv_my_point.setText(point + "");
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_extension, "商品推广", "说明", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        registerReceiver(receiver, "action.app.integral");
        inflater = LayoutInflater.from(this);
        user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        bean = (MyGoods.DataBean.ModelsBean) getIntent().getSerializableExtra("goods");
        if (bean != null) {
            if (user != null) {
                if (!Tools.isNull(user.getPoint())) {
                    point = user.getPoint();
                    tv_my_point.setText(point + "");
                }
            }
            promotionModel = new PreviewPromotionPresenter(this, mContext);
            gid = bean.getGid() + "";
            String specifications = bean.getSpecifications();
            String total_stock = bean.getTotal_stock();
            int num = bean.getNum();
            int is_expiring = bean.getIs_expiring();
            String packageX = bean.getPackageX();
            String thumb = bean.getThumb();
            String goods_name = bean.getGoods_name();
            String market_price = bean.getMarket_price();
            String country_name = bean.getCountry_name();
            if (!Tools.isNull(thumb)) {
                String path = "";
                if (thumb.startsWith("http")) {
                    path = thumb;
                } else {
                    path = HttpUtil.IMG_THUMB_BASE_URL + thumb;
                }
                Glide.with(getApplicationContext())
                        .load(path)
                        .centerCrop()
                        .placeholder(R.mipmap.loading_4b3)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(iv_banner);
            } else {
                iv_banner.setImageResource(R.mipmap.loading_4b3);
            }

            if (!Tools.isNull(num)) {
                tv_spec.setText("规格：" + num + specifications + "/" + packageX);
            } else {
                tv_spec.setText("规格：");
            }
            tv_goods_name.setText(goods_name);
            if (!Tools.isNull(market_price)) {
                tv_money.setText("￥" + market_price + "/" + packageX);
            } else {
                tv_money.setText("￥0件");
            }
            if (!Tools.isNull(country_name)) {
                tv_place.setText("产地：" + country_name);
            } else {
                tv_place.setText("产地：不详");
            }

            if (!Tools.isNull(total_stock)) {
                tv_stock.setText("库存：" + total_stock + packageX);
            } else {
                tv_stock.setText("库存：0件");
            }
            //1临期2正期
            switch (is_expiring) {
                case 1:
                    iv_expiring.setVisibility(View.VISIBLE);
                    break;
                case 2:
                    iv_expiring.setVisibility(View.INVISIBLE);
                    break;
            }
        }

    }

    @Override
    public void rightClick() {
        super.rightClick();
        startAct(ExtensionHttpActivity.class);
    }

    @OnClick({R.id.rl_extension, R.id.rl_apply, R.id.btn_exchange})
    public void onClick(View view) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        String hous = "";
        switch (view.getId()) {
            case R.id.rl_extension:
                hous = input_search_query.getText().toString().trim();
                if (Tools.isNull(hous)) {
                    T.showToast(mContext, "请先输入推广时间~");
                } else if (point == 0) {
                    T.showToast(mContext, "积分不足，请先充值~");
                } else {
                    intent.setClass(mContext, AvailableSaleActivity.class);
                    bundle.putString("gid", gid);
                    bundle.putString("tempId", areas);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                }
                break;
            case R.id.rl_apply:
                intent.setClass(mContext, IntegralRechargeActivity.class);
                startActivityForResult(intent, 300);
                break;
            case R.id.btn_exchange:
                point = user.getPoint();
                hous = input_search_query.getText().toString().trim();
                if (Tools.isNull(hous)) {
                    T.showToast(mContext, "请输入推广时间~");
                } else if (Tools.isNull(tv_city)) {
                    T.showToast(mContext, "请选择推广地区~");
                } else if (point < to_point) {
                    T.showToast(mContext, "积分不足，请先充值~");
                } else {
                    showProgressDialog(getString(R.string.app_loading));
                    goodsModel = new PromotionGoodsPresenter(this, mContext);
                    goodsModel.requestPromotionGoods(gid, hous, areas);
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    if (data != null) {
                        areas = data.getStringExtra("id");
                        String name = data.getStringExtra("name");
                        tv_city.setText(name);
                        String hous = input_search_query.getText().toString().trim();
                        promotionModel.requestPreviewPromotion(gid, hous, areas);
                    }
                    break;
                case 300:
                    // 刷新我的积分
                    memberInfoModel = new MemberInfoPresenter(this, mContext);
                    memberInfoModel.getMemberInfo();
                    break;
            }
        }
    }

    @Override
    public void promotionGoodsSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                int sumP = point - to_point;// 扣去推广所需积分
                user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                user.setPoint(sumP);
                App.getInstance().saveObject(user, HttpUtil.USER_KEY);
                setResult(RESULT_OK);
                finish();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void previewPromotionSuccess(PreviewM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                PreviewM.DataBean data = model.getData();
                values = data.getPromotions();
                to_point = data.getPoint();
                tv_to_point.setText(to_point + "");

                ll_root.removeAllViews();
                for (int i = 0; i < values.size(); i++) {
                    View inflate = inflater.inflate(R.layout.value_item, null);
                    TextView tv_content = (TextView) inflate.findViewById(R.id.tv_content);
                    tv_content.setText(values.get(i));
                    ll_root.addView(inflate);
                }
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void memberInfoSuccess(UserModel userModel) {
        if (userModel != null && userModel.getStatus() == HttpUtil.RESULT_OK) {
            User data = userModel.getData();
            data.setAuthToken(userModel.getAuthToken());
            App.getInstance().saveObject(data, HttpUtil.USER_KEY);
            user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
            if (user != null) {
                if (tv_my_point != null) {
                    tv_my_point.setText(user.getPoint() + "");
                }
            }
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


}
